<template>
	<view class="information_publish_layout">
		<uni-forms ref="form" :model="data" :rules="rules" err-show-type="toast">
			<uni-forms-item label="标题" label-align="right" required name="title">
				<uni-easyinput type="textarea" placeholder="请输入标题" v-model="data.title" :maxlength='-1'></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item label="作者" label-align="right" required name="auth">
				<uni-easyinput placeholder="请输入作者" v-model="data.auth" :maxlength='-1'></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item label="内容" label-align="right" required name="content">
				<uni-easyinput type="textarea" placeholder="请输入内容" v-model="data.content"
					:maxlength='-1'></uni-easyinput>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" @click="submit">提交</button>
			</view>
		</uni-forms>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';

	import {
		onLoad
	} from '@dcloudio/uni-app'

	const data = ref({
		_id: '',
		title: '',
		auth: '',
		content: '',
		type: 'ZX'
	})

	const form = ref(null)

	const rules = ref({
		title: {
			rules: [{
				required: true,
				errorMessage: '请输入标题',
			}]
		},
		auth: {
			rules: [{
				required: true,
				errorMessage: '请输入作者',
			}]
		},
		content: {
			rules: [{
				required: true,
				errorMessage: '请输入内容',
			}]
		}
	})

	const information = uniCloud.importObject('consultObj')

	onLoad(async (params) => {
		data.value.type = params.type
		// (ZX:报表资讯，ZN:报考指南，DG:考试大纲)
		const maps = {
			'ZX': '报表资讯',
			'ZN': '报考指南',
			'DG': '考试大纲'
		}
		uni.setNavigationBarTitle({
			title: `发布${maps[data.value.type]}`
		})
		if (!params.id) {
			return
		}
		let res = await information.information_detail(params.id)
		if (res.errCode != 0) {
			return
		}
		data.value = res.data
	})

	function submit() {
		form.value.validate().then((res) => {
			return submitForm(res)
		}).catch(() => {}).finally(() => {})
	}

	/**
	 * 提交表单
	 */
	async function submitForm(value) {
		let res = await information.information_publish(data.value)
		if (res.errCode != 0) {
			uni.showModal({
				content: res.errMsg || '请求服务失败',
				showCancel: false
			})
			return
		}
		uni.showToast({
			icon: 'none',
			title: data.value._id.length > 0 ? '修改成功' : '新增成功'
		})
		uni.$emit('information_change')
		uni.navigateBack()
	}
</script>

<style lang="scss" scoped>
	.information_publish_layout {
		padding: 0 40rpx;

		.uni-easyinput {
			font-size: 40rpx;
		}

		.uni-button {
			width: 184px;
		}
	}
</style>